package com.shanliao.controller;


import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanliao.model.User;
import com.shanliao.request.BaseRequest;
import com.shanliao.request.UserRegisterRequest;
import com.shanliao.respone.BaseResponse;
import com.shanliao.service.IUserService;
import com.shanliao.version.annatation.ApiVersion;
import com.shanliao.version.annatation.ApiVersionEnum;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jason
 * @since 2019-10-05
 */
@RestController
@RequestMapping("/{version}/user")
public class UserController extends BaseController{
	
	@Autowired
	private IUserService userService;
	@PostMapping("hello")
	@ApiVersion(ApiVersionEnum.v1_0_0)
	public ResponseEntity<String> hello6(@RequestBody @Valid BaseRequest<UserRegisterRequest> baseRequest){
		System.out.println("haha6.........");
		return responseData(BaseResponse.success(new User(), "返回用户信息"));
	}
	
	/**
	 * @Description: 用户注册/登录
	 */
	@PostMapping("/registOrLogin")
	public ResponseEntity<String> registOrLogin(@RequestBody @Valid BaseRequest<UserRegisterRequest> baseRequest){
		
		UserRegisterRequest userParam = baseRequest.getParam();
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.lambda().eq(User::getPhoneNum, userParam.getPhoneNum());
		// 1. 判断用户名是否存在，如果存在就登录，如果不存在则注册
		User user = userService.getOne(queryWrapper);
		if (user != null) {
			// 1.1 登录
			if(!StringUtils.equalsIgnoreCase(userParam.getPassword(), user.getPassword())) {
				return responseData(BaseResponse.fail("用户名或密码不正确..."));
			}
		} else {
			// 1.2 注册
			user = new User();
			user.setNickName(userParam.getNickName());
			user.setHeadUrl("");
			user.setPhoneNum(userParam.getPhoneNum());
			user.setPassword(userParam.getPassword());
			userService.save(user);
		}
		user.setPassword("");
		
		return responseData(BaseResponse.success(user, "返回用户信息"));
	}
	
}
